<template>
  <Page
    title="待办任务"
    description="处理待办任务，支持完成、转办、退回等操作"
  >
    <div class="flex h-full flex-col">
      <!-- 查询表单 -->
      <div class="mb-4 rounded-lg bg-white p-4">
        <Form layout="inline" :model="queryParams">
          <FormItem label="流程名称">
            <Input
              v-model:value="queryParams.processDefinitionName"
              placeholder="请输入流程名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="任务名称">
            <Input
              v-model:value="queryParams.taskName"
              placeholder="请输入任务名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleQuery">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>

      <!-- 数据表格 -->
      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'workflow:task:complete'"
                type="link"
                size="small"
                @click="handleComplete(row)"
              >
                办理
              </Button>
              <Button
                v-permission="'workflow:task:view'"
                type="link"
                size="small"
                @click="handleViewDiagram(row)"
              >
                流程图
              </Button>
              <Button
                v-permission="'workflow:task:transfer'"
                type="link"
                size="small"
                @click="handleDelegate(row)"
              >
                转办
              </Button>
              <Button
                v-permission="'workflow:task:reject'"
                type="link"
                size="small"
                @click="handleReturn(row)"
              >
                退回
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </div>

    <!-- 办理任务弹窗 -->
    <Modal
      v-model:open="completeModalVisible"
      title="办理任务"
      width="600px"
      @ok="handleSubmitComplete"
    >
      <Form
        ref="completeFormRef"
        :model="completeFormData"
        :rules="completeFormRules"
        layout="vertical"
      >
        <FormItem label="任务名称">
          <Input :value="currentTask?.name" disabled />
        </FormItem>
        <FormItem label="审批意见" name="comment">
          <TextArea
            v-model:value="completeFormData.comment"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </FormItem>
        <FormItem label="审批结果" name="approved">
          <RadioGroup v-model:value="completeFormData.approved">
            <Radio :value="true">同意</Radio>
            <Radio :value="false">拒绝</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
    </Modal>

    <!-- 转办任务弹窗 -->
    <Modal
      v-model:open="delegateModalVisible"
      title="转办任务"
      width="500px"
      @ok="handleSubmitDelegate"
    >
      <Form
        ref="delegateFormRef"
        :model="delegateFormData"
        :rules="delegateFormRules"
        layout="vertical"
      >
        <FormItem label="转办给" name="userId">
          <Input
            v-model:value="delegateFormData.userId"
            placeholder="请输入用户ID"
          />
        </FormItem>
        <FormItem label="转办原因" name="reason">
          <TextArea
            v-model:value="delegateFormData.reason"
            :rows="3"
            placeholder="请输入转办原因"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 退回任务弹窗 -->
    <Modal
      v-model:open="returnModalVisible"
      title="退回任务"
      width="500px"
      @ok="handleSubmitReturn"
    >
      <Form
        ref="returnFormRef"
        :model="returnFormData"
        :rules="returnFormRules"
        layout="vertical"
      >
        <FormItem label="退回到" name="targetActivityId">
          <Select
            v-model:value="returnFormData.targetActivityId"
            placeholder="请选择退回节点"
          >
            <SelectOption value="StartEvent_1">开始节点</SelectOption>
            <!-- TODO: 动态加载可退回的节点 -->
          </Select>
        </FormItem>
        <FormItem label="退回原因" name="reason">
          <TextArea
            v-model:value="returnFormData.reason"
            :rows="3"
            placeholder="请输入退回原因"
          />
        </FormItem>
      </Form>
    </Modal>
  </Page>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Form,
  FormItem,
  Input,
  Modal,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Space,
  message,
} from 'ant-design-vue';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

const { TextArea } = Input;

import type { UserTask } from '#/api/workflow';
import {
  completeTaskApi,
  delegateTaskApi,
  getTodoTaskListApi,
  returnTaskApi,
} from '#/api/workflow';

// 查询参数
const queryParams = reactive({
  processDefinitionName: undefined,
  taskName: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid<UserTask>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'processDefinitionName',
        title: '流程名称',
        minWidth: 200,
      },
      {
        field: 'name',
        title: '任务名称',
        minWidth: 150,
      },
      {
        field: 'assignee',
        title: '办理人',
        width: 120,
      },
      {
        field: 'createTime',
        title: '创建时间',
        minWidth: 180,
      },
      {
        field: 'dueDate',
        title: '到期时间',
        minWidth: 180,
      },
      {
        field: 'action',
        title: '操作',
        width: 280,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 办理任务相关
const completeModalVisible = ref(false);
const currentTask = ref<UserTask>();
const completeFormRef = ref();
const completeFormData = reactive({
  comment: '',
  approved: true,
});
const completeFormRules = {
  comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
  approved: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
};

// 转办任务相关
const delegateModalVisible = ref(false);
const delegateFormRef = ref();
const delegateFormData = reactive({
  userId: '',
  reason: '',
});
const delegateFormRules = {
  userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入转办原因', trigger: 'blur' }],
};

// 退回任务相关
const returnModalVisible = ref(false);
const returnFormRef = ref();
const returnFormData = reactive({
  targetActivityId: '',
  reason: '',
});
const returnFormRules = {
  targetActivityId: [
    { required: true, message: '请选择退回节点', trigger: 'change' },
  ],
  reason: [{ required: true, message: '请输入退回原因', trigger: 'blur' }],
};

// 查询列表
async function fetchList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getTodoTaskListApi(queryParams);
    gridApi.setState({
      gridOptions: {
        data: data.list,
        loading: false,
        pagerConfig: {
          currentPage: data.pageNum,
          pageSize: data.pageSize,
          total: data.total,
        },
      },
    });
  } catch (error: any) {
    message.error(error?.msg || '查询失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchList();
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchList();
}

// 重置
function handleReset() {
  queryParams.processDefinitionName = undefined;
  queryParams.taskName = undefined;
  queryParams.pageNum = 1;
  fetchList();
}

// 办理任务
function handleComplete(record: UserTask) {
  currentTask.value = record;
  completeFormData.comment = '';
  completeFormData.approved = true;
  completeModalVisible.value = true;
}

// 提交办理
async function handleSubmitComplete() {
  try {
    await completeFormRef.value.validate();
    await completeTaskApi(currentTask.value!.id!, {
      comment: completeFormData.comment,
      variables: {
        approved: completeFormData.approved,
      },
    });
    message.success('办理成功');
    completeModalVisible.value = false;
    await fetchList();
  } catch (error: any) {
    if (error?.msg) {
      message.error(error.msg);
    }
  }
}

// 查看流程图
function handleViewDiagram(record: UserTask) {
  // TODO: 打开流程图查看器
  message.info('功能开发中...');
}

// 转办任务
function handleDelegate(record: UserTask) {
  currentTask.value = record;
  delegateFormData.userId = '';
  delegateFormData.reason = '';
  delegateModalVisible.value = true;
}

// 提交转办
async function handleSubmitDelegate() {
  try {
    await delegateFormRef.value.validate();
    await delegateTaskApi(currentTask.value!.id!, delegateFormData.userId);
    message.success('转办成功');
    delegateModalVisible.value = false;
    await fetchList();
  } catch (error: any) {
    if (error?.msg) {
      message.error(error.msg);
    }
  }
}

// 退回任务
function handleReturn(record: UserTask) {
  currentTask.value = record;
  returnFormData.targetActivityId = '';
  returnFormData.reason = '';
  returnModalVisible.value = true;
}

// 提交退回
async function handleSubmitReturn() {
  try {
    await returnFormRef.value.validate();
    await returnTaskApi(
      currentTask.value!.id!,
      returnFormData.targetActivityId,
    );
    message.success('退回成功');
    returnModalVisible.value = false;
    await fetchList();
  } catch (error: any) {
    if (error?.msg) {
      message.error(error.msg);
    }
  }
}

// TODO: 后台接口未完成，暂时注释掉自动加载
// onMounted(() => {
//   fetchList();
// });

// 初始化空数据，避免页面报错
onMounted(() => {
  gridApi.setState({
    gridOptions: {
      data: [],
      loading: false,
    },
  });
});
</script>

